define(["moment"], function (moment) {
	return ["$scope", "$filter", "$stateParams", "config", "MMWService","$mdDialog", '$datePicker',
	function ($scope, $filter, $stateParams, config, $MMWService,$mdDialog, $datePicker) {
		$scope.init = function(){
			//每隻程式都有，等於window.onload方法
			$scope.C00_require_condition = true;
			var datasource_format_info = {};
			datasource_format_info.iselectd_filed = "0";
			datasource_format_info.column_info = [$filter('translate')('B0802.js.condition.column_1'),$filter('translate')('B0802.js.condition.column_2')];
			datasource_format_info.data_info = [[3,$filter('translate')('B0802.js.state_list.state_3')]];
            $scope.codeList = [
				{name:$filter('translate')('B0802.js.condition.code_2'), column_name:'A.ACCESSORYSTATE', data_type:'S',datasource_format_info:datasource_format_info},
				{name:$filter('translate')('B0802.js.condition.code_1'), column_name:'A.ACCESSORYNO'}
			];
			$scope.acc_data = [];
			$scope.select_all = false;
			$scope.is_inject = false;
			$scope.mode = "query";
			$scope.printList = []; // 列印詳情
		}
		
		$scope.back = function(){
            //返回首頁，傳入true表示使用退出
            $scope.$root.hideMenu();
            $scope.$root.changeProgram('home', true);//動畫
		}
		
		var pdf_url;
		$scope.confirm = function(){
			//確認按鈕
			var select_data = $filter('filter')($scope.acc_data,{is_select:1});
			if(select_data.length > 0)
			{
				var content = {};
				content.accessory_data = select_data;
				$MMWService.sendToServer({
					uri: 'ServicesSTD.Module_ACC.mold_runcard_pdf_get',
					content : content,
					success : function(data){
						if(data.mold_run_card_data.length > 0)
						{
							pdf_url = data.mold_run_card_data[0].url_pdf;

							for(var i = 0; i < content.accessory_data.length; i++){
								$scope.printList.push({
									printNo: content.accessory_data[i].accessory_no,
									printType: '5' // 1: 流程卡打印 + 生產批開立; 3: 條碼標籤打印(補印); 4: 外包單 - 出貨打印; 5. 叫修作業;
								});
							}

							if(pdf_url.indexOf('http://') == -1)
							{
                        		pdf_url = 'http://'+config.server.ip+':'+config.server.port+ pdf_url;
                    		}
							if(config.setting.outsidePDF == 'Y')
							{
                        		var fs = window.nodeRequire('fs'), RuncardPath;
								try
								{
									// 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
									const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                            		RuncardPath = remote.app.getAppPath();
								}
								catch(e)
								{
                            		RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                        		}
                        		RuncardPath += '\\www\\Runcard';
                        		if(!fs.existsSync(RuncardPath)){
                            		fs.mkdirSync(RuncardPath);
                        		}

								// 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
								// 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                        		fs.readdirSync(RuncardPath, (err, files) => {
									if (err) {
										console.log(err);
									}
									//listing all files using forEach
									files.forEach((file) => {
										// Do whatever you want to do with the file
										fs.unlink(RuncardPath + '/' + file, (err) => {
											if (err) {
												console.debug(err);
											}
										})
									});
								})
			
								// 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
								let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
								$scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
									// 20230807 modify by Alan for#130433 : electron升版後，shell.openItem改成shell.openPath
									const { shell } = window.nodeRequire('electron');
									shell.openItem ? shell.openItem(dist_path) : shell.openPath(dist_path);
								});
							} 
							else 
							{
                        		showPDFViewer(pdf_url);
                    		}
						}
					}
				});
			}
			else
			{
				$scope.$root.showAlert($filter('translate')('B0802.js.alert.error_0'));
			}
		}
		function showPDFViewer(pdf_url){
            try{
                window.nodeRequire('nw.gui').Window.open(pdf_url, {
                    title:'PDF Viewer',
                    show: false,
                    icon:'icon/icon.png',
                    focus:true
                }, function(win) {
                    win.on('loaded', function(){
                        win.show();
                        win.print();
                    });
                });
            } catch (e){
				$scope.mode = 'print';
                document.getElementById('kmi-pdf-panel').src = 'JSplugins/pdfjs/web/viewer.html?file='+pdf_url+'&openfile=false&viewbookmark=false&printfile=false&download=false#zoom=page-width';
            }
        }
		$scope.print = function(){
            if(window.nodeRequire){
                var sumatraPDF = window.nodeRequire('sumatra-pdf');
                if(sumatraPDF){
                    var fs = window.nodeRequire('fs'), RuncardPath;
                    try{
						const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                        RuncardPath = remote.app.getAppPath();
                    }catch(e){
                        RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                    }
                    RuncardPath += '\\www\\Runcard';
                    if(!fs.existsSync(RuncardPath)){
                        fs.mkdirSync(RuncardPath);
                    }

					// 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
					// 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
					fs.readdirSync(RuncardPath, (err, files) => {
						if (err) {
							console.log(err);
						}
						//listing all files using forEach
						files.forEach((file) => {
							// Do whatever you want to do with the file
							fs.unlink(RuncardPath + '/' + file, (err) => {
								if (err) {
									console.debug(err);
								}
							})
						});
					})

					// 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
					let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
					$scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                        $scope.$root.showLoading();
                        window.nodeRequire('sumatra-pdf').printWithSettings({
                            path: dist_path,
                            success:function(){
								printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                $scope.$root.hideLoading();
                                $scope.$root.showToast($filter('translate')('common.msg.success'));
                            },
                            error:function(error){
								// 20201104 modify by WeiTing for M#77013 - 不清楚為何在實際列印後，有列印成一張紙或輸出成 PDF檔案時，都會執行 error區域，所以目前 error區域也先當列印完成後，把列印詳情回送給後台做記錄。
                                printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                $scope.$root.hideLoading();
                                $scope.$root.showToast($filter('translate')('common.msg.success'));
                                //console.error(error);
                            }
                        });
                    });
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
            } else {
                window.frames['kmi-pdf-panel'].pdf_print();
            }
        };

        $scope.download = function(){
            window.frames['kmi-pdf-panel'].pdf_download();
        };

        $scope.cancel = function(){
            $scope.mode = 'query';
			document.getElementById('kmi-pdf-panel').src = '';
			$scope.printList = [];
        };

		function get_accessory_state_str(type)
		{
			var str ="";
			switch(type)
			{
				case "0":
					str = $filter('translate')('B0802.js.state_list.state_0');
				break;
				case "1":
					str = $filter('translate')('B0802.js.state_list.state_1');
				break;
				case "3":
					str = $filter('translate')('B0802.js.state_list.state_3');
					break;
			}
			return str;
		}
		$scope.select_all_acc_item = function()
		{
			if($scope.acc_data.length <= 0)
				return;
			var select_type = 0;
			if($scope.select_all)
			{
				select_type = 0;
				$scope.select_all = false;
			}
			else
			{
				select_type = 1;
				$scope.select_all = true;
			}
			for(var i in $scope.acc_data)
				$scope.acc_data[i].is_select = select_type;
		}
		$scope.select_acc_item = function(event,item)
		{
			if(item.is_select == 0)
				item.is_select = 1;
			else
				item.is_select = 0;
		}
		$scope.search = function(condition)
		{
			if(condition.length > 0)
			{
				$scope.acc_data = [];
				$scope.select_all = false;
				$scope.is_inject = false;
				var content = {};
				content.query_condition = condition;
				content.query_mode ="1";
				$MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_ACC.mold_maintenance_info_get',
                    content : content,
                    success : function(data){
						//console.log(data.info_data);
						if(data.info_data.length > 0)
						{
							$scope.is_inject = data.is_inject;
							$scope.acc_data = data.info_data
							for(var i in $scope.acc_data)
							{
								var state = ""+$scope.acc_data[i].accessory_state;
								$scope.acc_data[i].is_select = 0;
								$scope.acc_data[i].state_str =get_accessory_state_str(state);
								if($scope.acc_data[i].combine_acc == "1")
									$scope.acc_data[i].combine_str = $filter('translate')('B0802.js.state_list._1');
								else
									$scope.acc_data[i].combine_str = $filter('translate')('B0802.js.state_list._0');
							}
						}
                    },
                    error_callback:function(data){
                      
                    }
                });
			}
			else
			{
				$scope.$root.showAlert($filter('translate')('B0802.js.alert.error_6'));
			}
		}

		// 列印完成後，需把列印詳情回送給後台做記錄
		function printWiplogProcess(){
			$MMWService.sendToServer({
				uri: 'ServicesSTD.Module_SN.print_wiplog_process',
				content : {
                    printList: $scope.printList
                },
				success : function(){
					$scope.printList = [];
					$scope.mode = "query";
					$scope.beforeSearch();
				}
			});
		}
		
		// 列印詳情開窗查詢
		$scope.printInfoDialog = function(item){
			$mdDialog.dialog('module/moduleB/program/publicDialog/printInfoDialog.tmp.html',
                function(dialog){
                    return {
						printList: {
							program: 'B0802',
                            repair_order_no: item.accessory_no,  // 維修單單號
							print_user: '', // 列印人員
							start_date: moment().startOf('day').format('YYYY-MM-DD'), // 開始日期
							start_time: moment().startOf('day').format('HH:mm:ss'), // 開始時間
							end_date: moment().add(3, 'days').endOf('day').format('YYYY-MM-DD'), // 結束日期
							end_time: moment().add(3, 'days').endOf('day').format('HH:mm:ss'), // 結束時間
							printDetailList: []
						},
						init: function(){ // 初始化
							var start_dateTime = dialog.printList.start_date + ' ' + dialog.printList.start_time, // 開始日期 + 開始時間
								end_dateTime = dialog.printList.end_date + ' ' + dialog.printList.end_time; // 結束日期 + 結束時間

							$MMWService.pageNumberInfoGet({
								page_mode : 'print_wiplot_info_get',
								query_condition_info : [
									{column_name: 'PRINTNO', query_mode:'2', value: '%' + dialog.printList.repair_order_no + '%', merge_condition_model:'AND'}, // 維修單單號
									{column_name: 'CREATOR', query_mode:'2', value: '%' + dialog.printList.print_user + '%', merge_condition_model:'AND'}, // 列印人員
									{column_name: 'CREATEDATE', query_mode:'4', value: start_dateTime, merge_condition_model:'AND'}, // 列印时间 - 開始
									{column_name: 'CREATEDATE', query_mode:'5', value: end_dateTime, merge_condition_model:'AND'}, // 列印时间 - 結束
									{column_name: 'PRINTTYPE', query_mode:'0', value: '5', merge_condition_model:'AND'} // 列印類型 - 1:批次流程卡; 2:系统出站标签; 3:末站标签打印; 4:外包单打印; 5:模具维修单打印;
								]
							}, function (response) {
								if(response && response.length > 0){
									dialog.printList.printDetailList = response;
								} else {
									dialog.printList.printDetailList = [];
									$scope.$root.showAlert($filter('translate')('common.msg.no_data'));
								}
							});
						},
                        back: function() {
                            dialog.hide();
                        },
                        search: function() { // 查詢
							var start_dateTime = dialog.printList.start_date + ' ' + dialog.printList.start_time, // 開始日期 + 開始時間
								end_dateTime = dialog.printList.end_date + ' ' + dialog.printList.end_time; // 結束日期 + 結束時間

							$MMWService.pageNumberInfoGet({
								page_mode : 'print_wiplot_info_get',
								query_condition_info : [
									{column_name: 'PRINTNO', query_mode:'2', value: '%' + dialog.printList.repair_order_no + '%', merge_condition_model:'AND'}, // 維修單單號
									{column_name: 'CREATOR', query_mode:'2', value: '%' + dialog.printList.print_user + '%', merge_condition_model:'AND'}, // 列印人員
									{column_name: 'CREATEDATE', query_mode:'4', value: start_dateTime, merge_condition_model:'AND'}, // 列印时间 - 開始
									{column_name: 'CREATEDATE', query_mode:'5', value: end_dateTime, merge_condition_model:'AND'}, // 列印时间 - 結束
									{column_name: 'PRINTTYPE', query_mode:'0', value: '5', merge_condition_model:'AND'} // 列印類型 - 1:批次流程卡; 2:系统出站标签; 3:末站标签打印; 4:外包单打印; 5:模具维修单打印;
								]
							}, function (response) {
								if(response && response.length > 0){
									dialog.printList.printDetailList = response;
								} else {
									dialog.printList.printDetailList = [];
									$scope.$root.showAlert($filter('translate')('common.msg.no_data'));
								}
							});
                        },
                        changeStartDate: function() { // 更改開始日期
							$datePicker.open(dialog.printList.start_date,
								function(dialogType){
									if(moment(dialogType.datePacker.pickDate).isBefore(dialog.printList.end_date)
									|| moment(dialogType.datePacker.pickDate).isSame(dialog.printList.end_date))
									{
										dialog.printList.start_date = moment(dialogType.datePacker.pickDate).format('YYYY-MM-DD');
										dialogType.hide();
									}  
									else 
										$scope.$root.showAlert($filter('translate')('printInfoDialog.showAlert.column01')); // 開始日期不能大於結束日期！
								},
								function(dialogType){
									dialogType.hide();
								},{}
							);
                        },
                        changeEndDate: function() { // 更改結束日期
							$datePicker.open(dialog.printList.end_date,
								function(dialogType){
									if(moment(dialogType.datePacker.pickDate).isAfter(dialog.printList.start_date)
									|| moment(dialogType.datePacker.pickDate).isSame(dialog.printList.start_date))
									{
										dialog.printList.end_date = moment(dialogType.datePacker.pickDate).format('YYYY-MM-DD');
										dialogType.hide();
									}  
									else
										$scope.$root.showAlert($filter('translate')('printInfoDialog.showAlert.column02')); // 結束日期不能小於開始日期！
								},
								function(dialogType){
									dialogType.hide();
								},{}
							);
                        }
                    }
				}
			);
		};

	}
]});